package com.yiban.demo.Util;

import io.netty.util.NetUtil;
import lombok.SneakyThrows;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;

public class EncodeUtil {

    //因为messageDigest不为线程安全的
    @SneakyThrows
    public static String getSHA256(String s){
        MessageDigest sha256Instance = MessageDigest.getInstance("SHA-256");
        sha256Instance.update(s.getBytes(StandardCharsets.UTF_8));
        return byte2Hex(sha256Instance.digest());
    }
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    /**
     *
     * @param s 要被摘要的字符串
     * @return 32位md5
     */
    @SneakyThrows
    public static String getMD5(String s){
        MessageDigest md5Instance = MessageDigest.getInstance("MD5");
        md5Instance.update(s.getBytes(StandardCharsets.UTF_8));
        return byte2Hex(md5Instance.digest());
    }



}
